from django.template import Context, loader
from django.shortcuts import get_object_or_404, render_to_response
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from polls.models import Poll, Choice
from django.template import RequestContext
import logging
from mySerialize import getJson
from django.contrib import auth

def index(request):
	if not request.user.is_authenticated(): return render_to_response('polls/invalid.html')
	latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
	t = loader.get_template('polls/index.html')
	c = Context({
		'latest_poll_list': latest_poll_list,
		})
	return HttpResponse(t.render(c))


def detail(request, poll_id):
	if not request.user.is_authenticated(): return render_to_response('polls/invalid.html')
	
	p = get_object_or_404(Poll, pk=poll_id)
	return render_to_response('polls/detail.html', {'poll':p}, context_instance=RequestContext(request))

def vote(request, poll_id):
	if not request.user.is_authenticated(): return render_to_response('polls/invalid.html')
	
	p = get_object_or_404(Poll, pk=poll_id)
	try:
		selected_choice = p.choice_set.get(pk=request.POST['choice'])
		logging.info( "pk=" + request.POST['choice'] )
	except (KeyError, Choice.DoesNotExist):
		return render_to_response('polls/detail.html', {
			'poll': p,
			'error_message': "You didn't select a choice.",
			}, context_instance=RequestContext(request))
	else:
		selected_choice.votes += 1
		selected_choice.save()

		return HttpResponseRedirect(reverse('polls.views.results', args=(p.id,)))

def results(request, poll_id):
	if not request.user.is_authenticated(): return render_to_response('polls/invalid.html')
	
	p = get_object_or_404(Poll, pk=poll_id)
	return render_to_response('polls/results.html', {'poll':p})

def JsonExample(request):
	#return render_to_response('polls/json.html',{'JsonData': getJson()})
	return render_to_response('polls/timertest.html')
	#return HttpResponse(getJson(),mimetype="text/json")

def getJsonData(request):
	return HttpResponse(getJson(),mimetype="text/json")

def login(request):
	return render_to_response('polls/login.html', context_instance=RequestContext(request))

def logincheck(request):  
	username = request.POST['username']   
	password = request.POST['password']  
	user = auth.authenticate(username=username, password=password)
	if user is not None and user.is_active: 
		# Correct password, and the user is marked "active"  	
		auth.login(request, user)   
		# Redirect to a success page.   
		return HttpResponseRedirect("/polls/index/")  
		
	else:   
		# Show an error page   
		return render_to_response('polls/invalid.html')      
	
def logout(request):   
	auth.logout(request)
	# Redirect to a success page. 
	return HttpResponseRedirect("/polls/login/")     
